package com.plian.system.service.pm.investmentuprecord.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.GsonBuilder;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.plian.Tools.*;
import com.plian.Tools.office.WordUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.common.status.MyCustomCode;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dao.bt.baseinfo.BaseInfoDao;
import com.plian.system.entity.pm.appraisalreportback.AppraisalReportBack;
import com.plian.system.entity.pm.investmentuprecord.InvestmentupRecord;
import com.plian.system.entity.pm.ownershipstructureback.OwnershipStructureBack;
import com.plian.system.entity.pm.publiclist.PublicList;
import com.plian.system.mapper.pm.investmentuprecord.InvestmentupRecordMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.model.page.Page;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.pm.appraisalreportback.IAppraisalReportBackService;
import com.plian.system.service.pm.investmentuprecord.IInvestmentupRecordService;
import com.plian.system.service.pm.ownershipstructureback.IOwnershipStructureBackService;
import com.plian.system.service.pm.publiclist.IPublicListService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.vo.pm.appraisalreportback.AppraisalReportBackVO;
import com.plian.system.vo.pm.investmentuprecord.InvestmentupRecordVO;
import com.plian.system.vo.pm.ownershipstructureback.OwnershipStructureBackVO;
import com.plian.system.vo.pm.publiclist.PublicListVO;
import com.plian.system.wrapper.pm.appraisalreportback.AppraisalReportBackWrapper;
import com.plian.system.wrapper.pm.investmentuprecord.InvestmentupRecordWrapper;
import com.plian.system.wrapper.pm.ownershipstructureback.OwnershipStructureBackWrapper;
import com.plian.system.wrapper.pm.publiclist.PublicListWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.*;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
import static com.plian.system.constant.sys.FormTypeConstant.CQZC_INVESTMENTU_PRECORD;

/**
 * 增资扩股交易备案主表 服务实现类
 *
 */
@Slf4j
@Service
@AllArgsConstructor
public class InvestmentupRecordServiceImpl extends BaseServiceImpl<InvestmentupRecordMapper, InvestmentupRecord> implements IInvestmentupRecordService, BaseFlowService {
	private IOwnershipStructureBackService ownershipStructureBackService;
	private IAppraisalReportBackService appraisalReportBackService;
	private IFormCodeService formCodeService;
	private InvestmentupRecordMapper investmentupRecordMapper;
	private IPublicListService iPublicListService;
	@Autowired
	private BaseInfoDao baseInfoDao;
	@Autowired
	private Environment environment;

	private OwnershipStructureBackWrapper ownershipStructureBackWrapper;

	private AppraisalReportBackWrapper appraisalReportBackWrapper;

	private PublicListWrapper publicListWrapper;

	private InvestmentupRecordWrapper investmentupRecordWrapper;

	private GzwProperties gzwProperties;


	@Override
	public R<InvestmentupRecordVO> getDetailObj(InvestmentupRecordVO investmentupRecordVO){
		return R.data(setChild(investmentupRecordVO));
	}

	@Override
	public boolean saveOrUpdate(InvestmentupRecord investmentupRecord) {

		if (!Optional.ofNullable(investmentupRecord.getId()).isPresent()){
			investmentupRecord.setVersion("1");
			investmentupRecord.setCode(formCodeService.getCode(FormTypeConstant.CQZC_INVESTMENTU_PRECORD));
			investmentupRecord.setFormType(String.valueOf(FormTypeConstant.CQZC_INVESTMENTU_PRECORD));
		}

		if (Optional.ofNullable(investmentupRecord.getStatus()).isPresent() && investmentupRecord.getStatus() != -1){
			investmentupRecord.setStatus(investmentupRecord.getStatus());
		}

		return super.saveOrUpdate(investmentupRecord);
	}

	@Override
	public Boolean saveChild(InvestmentupRecordVO investmentupRecordVO) {
		try {
			List<OwnershipStructureBackVO> ownershipStructureBackVO = investmentupRecordVO.getOwnershipStructureBackVO();
			for (OwnershipStructureBackVO ownVo : ownershipStructureBackVO) {
				if (Optional.ofNullable(ownVo.getIsDeleted()).isPresent() && ownVo.getIsDeleted().intValue() == 1) {
					ownershipStructureBackService.removeById(ownVo.getId());
				} else {
					ownVo.setInvestmentupRecordId(investmentupRecordVO.getId().toString());
					ownershipStructureBackService.saveOrUpdate(ownVo);
				}
			}
			List<AppraisalReportBackVO> appraisalReportBackVO = investmentupRecordVO.getAppraisalReportBackVO();
			for (AppraisalReportBackVO subVo : appraisalReportBackVO) {
				if (Optional.ofNullable(subVo.getIsDeleted()).isPresent() && subVo.getIsDeleted().intValue() == 1) {
					appraisalReportBackService.removeById(subVo.getId());
				} else {
					subVo.setInvestmentupRecordId(investmentupRecordVO.getId().toString());
					appraisalReportBackService.saveOrUpdate(subVo);
				}
			}
			List<PublicListVO> publicListVO = investmentupRecordVO.getPublicListVO();
			for (PublicListVO pubvo : publicListVO) {
				if (Optional.ofNullable(pubvo.getIsDeleted()).isPresent() && pubvo.getIsDeleted().intValue() == 1) {
					iPublicListService.removeById(pubvo.getId());
				} else {
					pubvo.setInvestId(investmentupRecordVO.getId().toString());
					iPublicListService.saveOrUpdate(pubvo);
				}
			}
		}catch (Exception e){
			log.error(ExceptionUtils.getFullStackTrace(e));
			return false;
		}
		return true;
	}
	
	@Override
	public boolean deleteLogic(List<Long> ids) {
		for (Long id : ids) {
			InvestmentupRecord investmentupRecord = getById(id);
			if (investmentupRecord == null) {
				return false;
			} else if (investmentupRecord.getStatus() != null &&
					(investmentupRecord.getStatus() != FormStatusConstant.STASH && investmentupRecord.getStatus() != FormStatusConstant.UNREVIEWED)) {
				return false;
			}
		}
		return super.deleteLogic(ids);
	}

	@Override
	public InvestmentupRecordVO setChild(InvestmentupRecordVO investmentupRecordVO) {
		if(Optional.ofNullable(investmentupRecordVO).isPresent()) {
			investmentupRecordVO.setOwnershipStructureBackVO(ownershipStructureBackWrapper
					.entityToVO(ownershipStructureBackService
							.list(new LambdaQueryWrapper<OwnershipStructureBack>()
									.eq(OwnershipStructureBack::getInvestmentupRecordId,investmentupRecordVO.getId()))));

			investmentupRecordVO.setAppraisalReportBackVO(appraisalReportBackWrapper
					.entityToVO(appraisalReportBackService.list(new LambdaQueryWrapper<AppraisalReportBack>()
							.eq(AppraisalReportBack::getInvestmentupRecordId,investmentupRecordVO.getId()))));

			investmentupRecordVO.setPublicListVO(publicListWrapper
					.entityToVO(iPublicListService.list(new LambdaQueryWrapper<PublicList>()
							.eq(PublicList::getInvestId,investmentupRecordVO.getId()))));
		}
		return investmentupRecordVO;
	}
	@Override
	public HashMap<String,Object> commit(String id) {
		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

		//将需要提交的流程变量返回，用于工作流侧
		return new HashMap<String,Object>();
	}


	@Override
	public Boolean finish(String id)  {
		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
	}

	@Override
	public Boolean reject(String id, int formState, String comment) {
		return handleStatus(Long.valueOf(id), formState);
	}


	@Override
	public String checkIsSame(String id,String code) {
		String result = "";
		if (Optional.ofNullable(code).isPresent()) {
			InvestmentupRecord investmentupRecord = new InvestmentupRecord();
			investmentupRecord.setCode(code);
			if (Optional.ofNullable(getOne(Condition.getQueryWrapper(investmentupRecord))).isPresent()) {
				if (!getOne(Condition.getQueryWrapper(investmentupRecord)).getId().equals(id)) {
					result = "单据编码已存在";
				}
			}
		}
		return result;
	}

	@Override
	public Boolean checkIsExisted(Long id, String code) {
		if (Optional.ofNullable(code).isPresent()) {
			InvestmentupRecord investmentupRecord = new InvestmentupRecord();
			investmentupRecord.setCode(code);
			if (Optional.ofNullable(getOne(Condition.getQueryWrapper(investmentupRecord))).isPresent()) {
				if (id==null || !id.equals(getOne(Condition.getQueryWrapper(investmentupRecord)).getId())){
					return false;
				}
			}
		}
		return true;
	}

	@Override
	public ObjResult checkSubmit(InvestmentupRecord investmentupRecord) {

		if (!checkIsExisted(investmentupRecord.getId(), investmentupRecord.getCode())){
//            return R.fail("单据编码已存在");
			return new ObjResult(MyCustomCode.BILL_ALREADY_EXISTS2);
		}

		return null;
	}

	@Override
	public List<PageData> findByIds(List<String> formIds){
		QueryWrapper<InvestmentupRecord> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("id", Func.toLongList(org.apache.commons.lang3.StringUtils.join(formIds, StringPool.COMMA)));
		List<InvestmentupRecord> investmentupRecord = list(queryWrapper);
		List<InvestmentupRecordVO> investmentupRecordVOS = investmentupRecordWrapper.entityToVO(investmentupRecord);
		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(investmentupRecordVOS)){
				for (InvestmentupRecordVO vo : investmentupRecordVOS){
					vo.setUNITNAME(vo.getReportCompanyName());
					vo.setAPPLICANTNAME(vo.getCreateUserName());
					PageData pd = new PageData();
					pd.put("orgName", vo.getReportCompanyName());
					ObjectMapper mapper = new ObjectMapper();
					String json = new GsonBuilder().setDateFormat(DateUtil.PATTERN_DATETIME).create().toJson(vo);
					pd.putAll(mapper.readValue(json, new TypeReference<HashMap<String,String>>(){}));
					pageDataList.add(pd);
				}
			}
			return pageDataList;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		return pageDataList;
	}

	@Override
	public List<Integer> getFormType() {
		return Arrays.asList(CQZC_INVESTMENTU_PRECORD);
	}

	@Override
	public void goBackToStash(String formId) {
		handleStatus(Long.valueOf(formId), UNREVIEWED);
	}

	/**
	 *
	 * @param id		主键
	 * @param updateStatus 状态
	 * @return
	 */
	private Boolean handleStatus(Long id, int updateStatus) {
		try {
			InvestmentupRecord investmentupRecord = getById(id);
			if(updateStatus== FormStatusConstant.FINISH){
				String code =  formCodeService.getFilingCode(FormTypeConstant.CQZC_NPL_CANCEL_RECORD);
				investmentupRecord.setRecordCode(gzwProperties.getCodeStartName() + "核备〔"+code.substring(0,4)+"〕（"+code.substring(code.length()-3,code.length())+"）号");
			}
			investmentupRecord.setStatus(updateStatus);
			updateById(investmentupRecord);
			return true;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return false;
		}
	}
	@Override
	public ListResult<PageData> reportList(PageData pd){
		Page page=new Page(false,pd);
		try {
			List<PageData> list= investmentupRecordMapper.reportListPage(page);
			ListResult listResult=new ListResult(CommonCode.SUCCESS);
			listResult.setList(list);
			listResult.setTotal(page.getTotal());
			return listResult;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			throw new MyRuntimeException();
		}
	}

	@Override
	public File createReceptFile(Long id)  {
		InvestmentupRecord investmentupRecord = getById(id);
//		List<PageData> list=nPLCancelMaintainSubliDao.findById(pd.getString("id"));
		Document document = new Document(com.itextpdf.text.PageSize.A4, 10, 10, 30, 40);
		FileOutputStream fs;
		BaseFont bfHeiTi;
		BaseFont bfST;
		BaseFont test;
		BaseFont bfbt;
		File pdffile = null;
		try {
			pdffile = File.createTempFile(id.toString(), ".pdf");
			if (pdffile.exists()) {
				pdffile.delete();
			}
			fs = new FileOutputStream(pdffile.getPath());//getAbsolutePath
			PdfWriter.getInstance(document, fs);
			document.open();
			bfST = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			bfHeiTi = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			bfbt = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			test = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			// 添加标题
			Font font_Biaoti = new Font(bfHeiTi, 20.0f, Font.BOLD, BaseColor.BLACK);
			Font font_biaotou1 = new Font(test, 12.0f, Font.NORMAL, BaseColor.BLACK);
			Font font_biaotou2 = new Font(bfbt, 10.0f, Font.NORMAL, BaseColor.BLACK);
			Font font_Zhengwen = new Font(bfST, 11.0f, Font.NORMAL, BaseColor.BLACK);
			// 创建一个段落
			String title = "增资扩股交易备案表";
			Paragraph biaoti = new Paragraph(title, font_Biaoti);
			biaoti.setAlignment(1);
			biaoti.setSpacingAfter(20f);
			document.add(biaoti);
			// 创建副标题
			String recordCode=investmentupRecord.getRecordCode();
			if(recordCode==null){
				recordCode="";
			}
			String title1 = "备案编号:"+recordCode;
			Paragraph biaoti1 = new Paragraph(title1, font_biaotou1);
			biaoti1.setAlignment(Element.ALIGN_CENTER);
			biaoti1.setSpacingAfter(10f);
			document.add(biaoti1);

			String [] head={
					"股东名称",
					"出资额（万元）",
					"增资前出资比例(%)",
					"增资后出资比例(%)",
			};
			String [] kes={
					"shareholderName",
					"contributionCapital",
					"beforeFundedRatio",
					"afterFundedRatio"
			};
			PdfPTable table = new PdfPTable(head.length);// 建立一个pdf表格
			table.setWidths(new int[]{2,1,1,1});
			table.setSpacingBefore(10f);// 设置表格上面空白宽度
			table.setSpacingAfter(0f);// 设置表格下面空白宽度
			table.setSpacingBefore(10f);// 设置表格上面空白宽度
			table.setSpacingAfter(0f);// 设置表格下面空白宽度
			table.setTotalWidth(800);// 设置表格的宽度

			PdfPCell cell  = new PdfPCell(new Phrase("融资方名称", font_Zhengwen));
			cell.setMinimumHeight(30);
			// 由四列变成一列
			cell.setColspan(1);
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell.setPaddingBottom(5);
			cell.setPaddingTop(5);
			table.addCell(cell);
			PdfPCell  cell2 = new PdfPCell(new Phrase(investmentupRecord.getFinanciersName(), font_Zhengwen));
			// 由四列变成一列
			cell2.setColspan(3);
			cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell2.setPaddingBottom(5);
			cell2.setPaddingTop(5);
			table.addCell(cell2);

			PdfPCell cel3  = new PdfPCell(new Phrase("融资方企业性质", font_Zhengwen));
			cel3.setMinimumHeight(30);
			// 由四列变成一列
			cel3.setColspan(1);
			cel3.setHorizontalAlignment(Element.ALIGN_CENTER);
			cel3.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table.addCell(cel3);

			PageData p=new PageData();
			List<String> l=new ArrayList<>();
			l.add("061");
			p.put("parentId",l);
			List<Tree> base= baseInfoDao.findTree(p);

			for (Tree tree : base) {
				if(tree.getCode().equals(investmentupRecord.getFinanciersNatureId())){
					investmentupRecord.setFinanciersNatureId(tree.getName());
					break;
				}
			}
			PdfPCell  cell4 = new PdfPCell(new Phrase(investmentupRecord.getFinanciersNatureId(), font_Zhengwen));
			// 由四列变成一列
			cell4.setColspan(3);
			cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table.addCell(cell4);


			PdfPCell cel5 = new PdfPCell(new Phrase("融资额（万元）", font_Zhengwen));
			cel5.setMinimumHeight(30);
			// 由四列变成一列
			cel5.setColspan(1);
			cel5.setHorizontalAlignment(Element.ALIGN_CENTER);
			cel5.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table.addCell(cel5);

			PdfPCell  cell6 = new PdfPCell(new Phrase(isnull(investmentupRecord.getFinanciersAmount()), font_Zhengwen));
			// 由四列变成一列
			cell6.setColspan(3);
			cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table.addCell(cell6);

			PdfPCell  cell7 = new PdfPCell(new Phrase("增资前后股权结构", font_Zhengwen));
			// 由四列变成一列
			cell7.setColspan(4);
			cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell7.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell7.setPaddingBottom(5);
			cell7.setPaddingTop(5);
			cell7.setMinimumHeight(30);
			table.addCell(cell7);


			for (int i = 0; i < head.length; i++) {
				String s = head[i];
				PdfPCell cell8  =new PdfPCell(new Phrase(s, font_Zhengwen));
				cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell8.setVerticalAlignment(Element.ALIGN_MIDDLE);
				cell8.setPaddingBottom(5);
				cell8.setPaddingTop(5);
				cell8.setMinimumHeight(30);
				table.addCell(cell8);
			}


			List<OwnershipStructureBackVO> list =ownershipStructureBackWrapper.entityToVO(ownershipStructureBackService
					.list(new LambdaQueryWrapper<OwnershipStructureBack>().eq(OwnershipStructureBack::getInvestmentupRecordId, investmentupRecord.getId())));

			for (OwnershipStructureBackVO ownershipStructureBack : list) {
				PdfPCell cell8  =new PdfPCell(new Phrase(ownershipStructureBack.getShareholderName(), font_Zhengwen));
				cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell8.setVerticalAlignment(Element.ALIGN_MIDDLE);
				cell8.setMinimumHeight(30);
				table.addCell(cell8);

				PdfPCell cell9  =new PdfPCell(new Phrase(isnull(ownershipStructureBack.getContributionCapital()), font_Zhengwen));
				cell9.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell9.setVerticalAlignment(Element.ALIGN_MIDDLE);
				table.addCell(cell9);

				PdfPCell cell10  =new PdfPCell(new Phrase(isnull(ownershipStructureBack.getBeforeFundedRatio()), font_Zhengwen));
				cell10.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell10.setVerticalAlignment(Element.ALIGN_MIDDLE);
				table.addCell(cell10);

				PdfPCell cell11  =new PdfPCell(new Phrase(isnull(ownershipStructureBack.getAfterFundedRatio()), font_Zhengwen));
				cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell11.setVerticalAlignment(Element.ALIGN_MIDDLE);
				table.addCell(cell11);
			}

			PdfPTable table1 = new PdfPTable(3);// 建立一个pdf表格

			PdfPCell cell8  =new PdfPCell(new Phrase("决策文件", font_Zhengwen));
			cell8.setMinimumHeight(30);
			cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell8.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table1.addCell(cell8);

			PdfPCell cell9  =new PdfPCell(new Phrase(investmentupRecord.getDecisionDoc(), font_Zhengwen));
			cell9.setColspan(2);
			cell9.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell9.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table1.addCell(cell9);


			List<AppraisalReportBackVO> list1 = appraisalReportBackWrapper.entityToVO(appraisalReportBackService
							.list(new LambdaQueryWrapper<AppraisalReportBack>().eq(AppraisalReportBack::getInvestmentupRecordId, investmentupRecord.getId())));
			PdfPCell cell10  =new PdfPCell(new Phrase("评估报告", font_Zhengwen));
			cell10.setRowspan(list1.size()+1);
			cell10.setMinimumHeight(30);
			cell10.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell10.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table1.addCell(cell10);

			PdfPCell cell11  =new PdfPCell(new Phrase("文    号", font_Zhengwen));
			cell11.setMinimumHeight(30);
			cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell11.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table1.addCell(cell11);

			PdfPCell cell12  =new PdfPCell(new Phrase("评 估 价(万元)", font_Zhengwen));
			cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell12.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table1.addCell(cell12);


			for (AppraisalReportBackVO appraisalReportBack : list1) {
				PdfPCell cell17  =new PdfPCell(new Phrase(appraisalReportBack.getEvaluationReportNum(), font_Zhengwen));
				cell17.setMinimumHeight(30);
				cell17.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell17.setVerticalAlignment(Element.ALIGN_MIDDLE);
				table1.addCell(cell17);

				PdfPCell cell18  =new PdfPCell(new Phrase(isnull(appraisalReportBack.getEvaluationPrice()), font_Zhengwen));
				cell18.setColspan(2);
				cell18.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell18.setVerticalAlignment(Element.ALIGN_MIDDLE);
				table1.addCell(cell18);
			}


			PdfPCell cell13  =new PdfPCell(new Phrase("遴选方式", font_Zhengwen));
			cell13.setMinimumHeight(30);
			cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell13.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table1.addCell(cell13);

			PdfPCell cell14  =new PdfPCell(new Phrase(investmentupRecord.getSelectionMethod(), font_Zhengwen));
			cell14.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell14.setColspan(2);
			cell14.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table1.addCell(cell14);


			PdfPCell cell15  =new PdfPCell(new Phrase("投资者", font_Zhengwen));
			cell15.setMinimumHeight(30);
			cell15.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell15.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table1.addCell(cell15);

			PdfPCell cell16  =new PdfPCell(new Phrase(investmentupRecord.getInvestor(), font_Zhengwen));
			cell16.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell16.setColspan(2);
			cell16.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table1.addCell(cell16);

			PdfPTable table2 = new PdfPTable(3);// 建立一个pdf表格
			PdfPCell cell19  =new PdfPCell(new Phrase("\n意\n\n\n" +
					"见\n\n\n" +
					"及\n\n\n" +
					"签\n\n\n" +
					"章\n\n\n", font_Zhengwen));
			cell19.setMinimumHeight(60);
			cell19.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell19.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table2.addCell(cell19);


			PdfPCell cell20  =new PdfPCell(new Phrase("填报单位意见\n\n\n\n\n\n                                  同意上报\n" +
					"                                （盖章）\n\n\n\n\n\n\n\n                           年         月         日", font_Zhengwen));
			cell20.setMinimumHeight(30);
			cell20.setHorizontalAlignment(Element.ALIGN_LEFT);
			table2.addCell(cell20);

			PdfPCell cell21  =new PdfPCell(new Phrase("国资监管部门意见\n\n\n\n\n\n                                  同意上报\n" +
					"                                （盖章）\n\n\n\n\n\n\n\n                           年         月         日", font_Zhengwen));
			cell21.setMinimumHeight(30);
			cell21.setHorizontalAlignment(Element.ALIGN_LEFT);
			table2.addCell(cell21);

			document.add(table);
			document.add(table1);
			document.add(table2);
			document.close();
			return pdffile;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return null;
		}

	}

	public String isnull(BigDecimal s) {
		if (s==null) {
			return "";
		} else {
			return s.toPlainString();
		}
	}

	@Override
	public File buildword(String id, HttpServletResponse response) {
		InvestmentupRecordVO bean = investmentupRecordWrapper.entityToVO(getById(id));
		File file = null;
		try {
			if (bean != null) {
				Map<String, Object> data = new HashMap<>(16);
				data.put("recordCode", bean.getRecordCode());
				data.put("financiersName", bean.getFinanciersName());
				PageData natureId = baseInfoDao.findbycode(bean.getFinanciersNatureId());
				data.put("financiersNatureName",natureId!=null?natureId.getString("name"):"");
				data.put("decisionDoc",bean.getDecisionDoc());
				data.put("selectionMethod",bean.getSelectionMethod());
				data.put("investor",bean.getInvestor());

				AppraisalReportBack appraisalReportBack = new AppraisalReportBack();
				appraisalReportBack.setInvestmentupRecordId(String.valueOf(bean.getId()));
				List<AppraisalReportBackVO> appraisalReportBackVOS = appraisalReportBackWrapper.entityToVO(appraisalReportBackService.list(Condition.getQueryWrapper(appraisalReportBack)));
				if (CollectionUtil.isNotEmpty(appraisalReportBackVOS)) {
					data.put("appraisalReportBackVOS", appraisalReportBackVOS);
				}

				OwnershipStructureBack ownershipStructureBack = new OwnershipStructureBack();
				ownershipStructureBack.setInvestmentupRecordId(String.valueOf(bean.getId()));
				List<OwnershipStructureBackVO> ownershipStructureBackVOS = ownershipStructureBackWrapper.entityToVO(ownershipStructureBackService.list(Condition.getQueryWrapper(ownershipStructureBack)));
				if (CollectionUtil.isNotEmpty(ownershipStructureBackVOS)) {
					data.put("ownershipStructureBackVOS", ownershipStructureBackVOS);
				}

				PublicList publicList = new PublicList();
				publicList.setInvestId(String.valueOf(bean.getId()));
				List<PublicListVO> publicListVOS = publicListWrapper.entityToVO(iPublicListService.list(Condition.getQueryWrapper(publicList)));
				if (CollectionUtil.isNotEmpty(publicListVOS)) {
					for (PublicListVO publicListVO : publicListVOS) {
						if (publicListVO.getDealPrice() != null) {
                            data.put("dealPrice", publicListVO.getDealPrice());
                        }
					}
				}

				String realPath = environment.getProperty("doc.path") + id + ".doc";
				file = WordUtil.generateWord(data, realPath, "investmentupRecord.doc", "investmentupRecord.ftl");
				response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
				InputStream inputStream = new FileInputStream(file);
				// 激活下载操作
				OutputStream os = response.getOutputStream();
				// 循环写入输出流
				byte[] b = new byte[2048];
				int length;
				while ((length = inputStream.read(b)) > 0) {
					os.write(b, 0, length);
				}
				// 这里主要关闭。
				os.close();
				inputStream.close();
			}

		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		return file;
	}
}
